package netty.util;

import java.text.DecimalFormat;

/**
 * 文件名称：ByteUtil 创建时间：2018-11-09 16:41 文件作者：shihuijuan 功能描述：字节工具类
 */
public class ByteUtil {
    private final static int HEX = 2;

    /**
     * 字节数组转换成对应的16进制表示的字符串
     *
     * @param src
     * @return
     */
    public static String bytes2HexStr(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return "";
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            builder.append(buffer);
        }
        return builder.toString().toUpperCase();
    }

    /**
     * 字符转16进制表示的字符串
     */
    public static String bytes2HexStr(byte src) {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[2];
        buffer[0] = Character.forDigit((src >>> 4) & 0x0F, 16);
        buffer[1] = Character.forDigit(src & 0x0F, 16);
        builder.append(buffer);
        return builder.toString().toUpperCase();
    }

    /**
     * 十六进制字节数组转字符串
     *
     * @param src    目标数组
     * @param dec    起始位置
     * @param length 长度
     * @return
     */
    public static String bytes2HexStr(byte[] src, int dec, int length) {
        byte[] temp = new byte[length];
        System.arraycopy(src, dec, temp, 0, length);
        return bytes2HexStr(temp);
    }

    public static void copy(byte[] src, int offset, int length, byte[] dest) {
        for (int i = 0; i < length; i++) {
            dest[i] = src[offset + i];
        }
    }

    /**
     * 16进制字符串转10进制数字
     *
     * @param hex
     * @return
     */
    public static long hexStr2decimal(String hex) {
        return Long.parseLong(hex, 16);
    }

    /**
     * 把十进制数字转换成足位的十六进制字符串,并补全空位
     *
     * @param num
     * @return
     */
    public static String decimal2fitHex(long num) {
        String hex = Long.toHexString(num).toUpperCase();
        if (hex.length() % HEX != 0) {
            return "0" + hex;
        }
        return hex.toUpperCase();
    }

    /**
     * 把十进制数字转换成足位的十六进制字符串,并补全空位
     *
     * @param num
     * @param strLength 字符串的长度
     * @return
     */
    public static String decimal2fitHex(long num, int strLength) {
        String hexStr = decimal2fitHex(num);
        StringBuilder stringBuilder = new StringBuilder(hexStr);
        while (stringBuilder.length() < strLength) {
            stringBuilder.insert(0, '0');
        }
        return stringBuilder.toString();
    }

    public static String fitDecimalStr(int dicimal, int strLength) {
        StringBuilder builder = new StringBuilder(String.valueOf(dicimal));
        while (builder.length() < strLength) {
            builder.insert(0, "0");
        }
        return builder.toString();
    }

    /**
     * 字符串转十六进制字符串
     *
     * @param str
     * @return
     */
    public static String str2HexString(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder();
        byte[] bs = null;
        try {

            bs = str.getBytes("utf8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString();
    }

    /**
     * 把十六进制表示的字节数组字符串，转换成十六进制字节数组
     *
     * @param
     * @return byte[]
     */
    public static byte[] hexStr2bytes(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toUpperCase().toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (hexChar2byte(achar[pos]) << 4 | hexChar2byte(achar[pos + 1]));
        }
        return result;
    }

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] hextoBytes(String str) {
        if (str == null || str.trim().isEmpty()) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / HEX; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }

    /**
     * 把16进制字符[0123456789abcde]（含大小写）转成字节
     *
     * @param c
     * @return
     */
    private static int hexChar2byte(char c) {
        switch (c) {
        case '0':
            return 0;
        case '1':
            return 1;
        case '2':
            return 2;
        case '3':
            return 3;
        case '4':
            return 4;
        case '5':
            return 5;
        case '6':
            return 6;
        case '7':
            return 7;
        case '8':
            return 8;
        case '9':
            return 9;
        case 'a':
        case 'A':
            return 10;
        case 'b':
        case 'B':
            return 11;
        case 'c':
        case 'C':
            return 12;
        case 'd':
        case 'D':
            return 13;
        case 'e':
        case 'E':
            return 14;
        case 'f':
        case 'F':
            return 15;
        default:
            return -1;
        }
    }

    /**
     * 十六进制字符串转换成字符串
     *
     * @param hexStr
     * @return String
     */
    public static String hexStr2Str(String hexStr) {

        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 多个byte数组合成一个
     *
     * @param values
     * @return
     */
    public static byte[] byteMerge(byte[]... values) {
        int length = 0;
        for (int i = 0; i < values.length; i++) {
            length += values[i].length;
        }
        byte[] result = new byte[length];
        int countLength = 0;
        for (int i = 0; i < values.length; i++) {
            byte[] b = values[i];
            System.arraycopy(b, 0, result, countLength, b.length);
            countLength += b.length;
        }
        return result;
    }

    /**
     * byte数组转化为整数
     *
     * @param b 2个字节数组
     * @return
     */
    public static int byteArrayToInt(byte[] b) {
        if (b.length == 1) {
            return b[0] & 0xFF;
        } else if (b.length == 2) {
            return b[1] & 0xFF | (b[0] & 0xFF) << 8;
        } else if (b.length == 3) {
            return b[2] & 0xFF | (b[1] & 0xFF) << 8 | (b[0] & 0xff) << 16;
        } else if (b.length == 4) {
            return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xff) << 16 | (b[0] & 0xff) << 24;
        }
        return 0;

    }

    /**
     * byte转化为整数
     *
     * @param b
     * @return
     */
    public static int byteToInt(byte b) {
        // Java 总是把 byte 当做有符处理；我们可以通过将其和 0xFF 进行二进制与得到它的无符值
        return b & 0xFF;
    }

    /**
     * 整数转换为2个字节数组
     *
     * @param a
     * @return
     */
    public static byte[] intToByteArray(int a) {
        return new byte[] { (byte) ((a >> 8) & 0xFF), (byte) (a & 0xFF) };
    }

    /**
     * 16进制转2进制(16位)
     */
    public static String hexStringTo2Byte(String hex) {
        int i = Integer.parseInt(hex, 16);
        String str2 = Integer.toBinaryString(i);
        String str3 = "";

        if (str2.length() < 16) {
            for (int j = 0; j < 16 - str2.length(); j++) {
                str3 = str3 + "0";
            }
            str2 = str3 + str2;
        }

        return str2;
    }

    /**
     * 16进制转2进制(8位)
     */
    public static String hexStringToByte(String hex) {
        int i = Integer.parseInt(hex, 16);
        String str2 = Integer.toBinaryString(i);
        String str3 = "";

        if (str2.length() < 8) {
            for (int j = 0; j < 8 - str2.length(); j++) {
                str3 = str3 + "0";
            }
            str2 = str3 + str2;
        }

        return str2;
    }

    /**
     * 字节转浮点数
     *
     * @param bytes
     * @return
     */
    public static String byteToDecimal(String bytes) {

        String newBytes = "";
        DecimalFormat df = new DecimalFormat("0.0");
        if ("0".equals(bytes.charAt(0) + "")) {
            newBytes = bytes;
            return df.format(Integer.valueOf(newBytes, 2) * 0.1) + "";
        } else {
            for (int i = 0; i < bytes.length(); i++) {
                char c = bytes.charAt(i);
                if ("0".equals(c + "")) {
                    newBytes = newBytes + "1";
                } else {
                    newBytes = newBytes + "0";
                }
            }

            return "-" + df.format((Integer.valueOf(newBytes, 2) + 1) * 0.1);
        }

    }

    public static float byte2float(byte[] bytes, int index) {
        //低字节在后
        int l=(0xff & bytes[index+3]) | (0xff00 & (bytes[index +2] << 8)) | (0xff0000 & (bytes[index +1] << 16)) | (0xff000000 & (bytes[index] << 24));
        return Float.intBitsToFloat(l);
    }

    public static byte[] float2byte(float f) {

        // 把float转换为byte[]
        int fbit = Float.floatToIntBits(f);

        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (fbit >> (24 - i * 8));
        }

        // 翻转数组
        int len = b.length;
        // 建立一个与源数组元素类型相同的数组
        byte[] dest = new byte[len];
        // 为了防止修改源数组，将源数组拷贝一份副本
        System.arraycopy(b, 0, dest, 0, len);
        byte temp;
        // 将顺位第i个与倒数第i个交换
        for (int i = 0; i < len / 2; ++i) {
            temp = dest[i];
            dest[i] = dest[len - i - 1];
            dest[len - i - 1] = temp;
        }

        return dest;

    }

    public static String floatToHex(float data) {
        int temp = (int) (data * 10);
        String str2 = Integer.toHexString(temp);
        String str3 = "";
        if (str2.length() < 4) {
            for (int j = 0; j < 4 - str2.length(); j++) {
                str3 = str3 + "0";
            }
            str2 = str3 + str2;
        } else if (str2.length() == 8) {
            str2 = str2.substring(4, 8);
        }
        return str2;
    }

    /**
     * 整数转字节
     *
     * @param x
     * @return
     */
    public static byte intToByte(int x) {
        return (byte) x;
    }

    public static int convertIntByBig(byte[] data) {
        if (data.length == 1) {
            return data[0] & 0xff;
        } else if (data.length == 2) {
            return data[0] & 0xff | (data[1] & 0xff) << 8;
        } else if (data.length == 3) {
            return data[0] & 0xff | (data[1] & 0xff) << 8 | (data[2] & 0xff) << 16;
        } else if (data.length >= 4) {
            return data[0] & 0xff | (data[1] & 0xff) << 8 | (data[2] & 0xff) << 16 | (data[3] & 0xff) << 24;
        }
        return 0;
    }

    public static int convertIntByLittle(byte[] data) {
        if (data.length == 1) {
            return data[0] & 0xff;
        } else if (data.length == 2) {
            return data[1] & 0xff | (data[0] & 0xff) << 8;
        } else if (data.length == 3) {
            return data[2] & 0xff | (data[1] & 0xff) << 8 | (data[0] & 0xff) << 16;
        } else if (data.length >= 4) {
            return data[3] & 0xff | (data[2] & 0xff) << 8 | (data[1] & 0xff) << 16 | (data[0] & 0xff) << 24;
        }
        return 0;
    }

    public static byte[] sumCheck(byte[] msg, int length) {
        long mSum = 0;
        byte[] mByte = new byte[length];

        /** 逐Byte添加位数和 */
        for (byte byteMsg : msg) {
            long mNum = ((long) byteMsg >= 0) ? (long) byteMsg : ((long) byteMsg + 256);
            mSum += mNum;
        } /** end of for (byte byteMsg : msg) */

        /** 位数和转化为Byte数组 */
        for (int liv_Count = 0; liv_Count < length; liv_Count++) {
            mByte[length - liv_Count - 1] = (byte) (mSum >> (liv_Count * 8) & 0xff);
        } /** end of for (int liv_Count = 0; liv_Count < length; liv_Count++) */

        return mByte;
    }

    public static long intToLong(int i) {
        return i & 0x0ffffffffl;
    }

    public static int byte2int(byte[] bytes, int i) {
        return convertIntByLittle(new byte[]{bytes[i],bytes[i+3]});
    }

    /**
     * 把单个字节转换成二进制字符串
     */
    public static String byteToBin(byte b) {
        String zero = "00000000";
        String binStr = Integer.toBinaryString(b & 0xFF);
        if(binStr.length() < 8) {
            binStr = zero.substring(0, 8 -binStr.length()) + binStr;
        }
        return binStr;
    }

    /**
     * 获取字节在内存中某一位的值,采用字符取值方式
     */
    public static int getBitByByte(byte b, int index) {
        if(index >= 8) { return 0; }
        String binStr = byteToBin(b);
        return Integer.parseInt(String.valueOf(binStr.charAt(index)));
    }

}
